import notificationService from './notification'

class GlobalReminderService {
  constructor() {
    this.triggeredReminders = new Set()
    this.checkInterval = null
    this.lastCheckDate = new Date().toDateString()
  }

  start() {
    // 请求通知权限
    if (Notification.permission === 'default') {
      Notification.requestPermission()
    }

    // 每秒检查一次提醒
    this.checkInterval = setInterval(() => {
      this.checkAllReminders()
    }, 1000)
  }

  stop() {
    if (this.checkInterval) {
      clearInterval(this.checkInterval)
      this.checkInterval = null
    }
  }

  padZero(num) {
    return (num < 10 ? '0' : '') + num
  }

  checkAllReminders() {
    const now = new Date()
    const currentDate = now.toDateString()

    // 每天重置已触发的提醒
    if (currentDate !== this.lastCheckDate) {
      this.triggeredReminders.clear()
      this.lastCheckDate = currentDate
    }

    // 检查今天和明天的计划
    const currentYear = now.getFullYear()
    const currentMonth = now.getMonth() + 1
    const currentDay = now.getDate()

    for (let dayOffset = 0; dayOffset <= 1; dayOffset++) {
      const checkDate = new Date(currentYear, currentMonth - 1, currentDay + dayOffset)
      const year = checkDate.getFullYear()
      const month = this.padZero(checkDate.getMonth() + 1)
      const day = this.padZero(checkDate.getDate())
      const planKey = `${year}-${month}-${day}`

      // 从localStorage获取该日期的所有计划
      const plans = JSON.parse(localStorage.getItem(planKey)) || []

      // 检查每个计划的提醒时间
      plans.forEach((plan, index) => {
        if (plan.reminderTime) {
          const reminderTime = new Date(plan.reminderTime)
          const timeDiff = Math.abs(reminderTime - now)
          
          // 生成唯一的提醒标识
          const reminderId = `${planKey}-${index}-${plan.reminderTime}`

          // 如果提醒时间已到且未触发过
          if (timeDiff <= 60000 && !this.triggeredReminders.has(reminderId)) {
            // 标记为已触发
            this.triggeredReminders.add(reminderId)
            
            // 显示通知
            notificationService.show({
              title: '计划提醒',
              message: `计划"${plan.title}"已超时，请及时处理！`,
              type: 'warning',
              playSound: true
            })
          }
        }
      })
    }
  }
}

export default new GlobalReminderService() 